# -*-encoding:utf-8-*-
u"""系统节点模块.
"""
import json
from flask import Blueprint, g
from psycopg2 import connect
from psycopg2.extras import RealDictCursor
from config import config
from lib import auth
from lib.table import table
from lib.validform import V, ValidateForm

app = Blueprint(__name__ + "_app", __name__)


@app.before_request
def setupdb():
    u"""构造函数."""
    g.conn = connect(**config.DatabaseConfig.siem)
    g.cursor = g.conn.cursor(cursor_factory=RealDictCursor)


@app.teardown_request
def unsetdb(exception):
    u"""析构函数."""
    if g.cursor:
        g.cursor.close()
        g.cursor = None
    if g.conn:
        g.conn.close()
        g.conn = None


# @app.route('/api/important/check', methods=['POST'])
# def check_name():
#     u"""检查名字重复."""
#     try:
#         form = ValidateForm(
#             import_title=['重保标题', V.required()]
#         )
#         (flag, data) = form.validate()
#         if not flag:
#             data['status'] = 'fail'
#             return json.dumps(data)
#         g.cursor.execute(""" select count(1) as num from h_import_protect_info where state ='1' and import_title = '%s'""" % (data['import_title']))
#         total = g.cursor.fetchone()['num']
#         return json.dumps({
#             "status": "success",
#             "data": total
#         })
#     except Exception, e:
#         return json.dumps({"status": "except", 'msg': '查询失败'})


@app.route('/api/systemNode/list', methods=['POST'])
def get_important():
    u"""获取系统节点列表."""
    try:
        tb = table()
        g.cursor.execute("""select count(1) as num from h_system_node as a
        left join h_information_system as b on a.info_sys_id = b.info_sys_id
        left join sys_agency_info as c on b.agency_id = c.agency_id %s """ % (tb.where(['a.sys_node_name'], "a.state='1'")))
        total = g.cursor.fetchone()['num']
        g.cursor.execute("""select a.sys_node_id as asys_node_id, a.sys_node_name as asys_node_name, a.sys_node_code as asys_node_code, a.node_type as anode_type, a.oprate_system as aoprate_system, a.confi_lv_id ||'级' as aconfi_lv_id, a.is_register as ais_register,d2t(a.r_time) as ar_time, b.info_sys_name as binfo_sys_name, c.agency_name as cagency_name from h_system_node as a
        left join h_information_system as b on a.info_sys_id = b.info_sys_id
        left join sys_agency_info as c on b.agency_id = c.agency_id %s %s %s %s""" % (tb.where(['a.sys_node_name'], "a.state='1'"), tb.orderBy(), tb.offset(), tb.limit()))
        return json.dumps({
            "status": "success",
            "data": {
                "current": tb.current(),
                "total": total,
                "dataSource": g.cursor.fetchall()
            }
        })
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败', "warn": str(e)})


@app.route('/api/systemNode/details', methods=['get'])
@auth.permission('systemNode')
def get_details(_currUser):
    u"""查询重保详情."""
    try:
        form = ValidateForm(
            sys_node_id=['系统节点id', V.required()]
        )
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        g.cursor.execute("""select a.sys_node_name as asys_node_name, 
                                   a.sys_node_des as asys_node_des, 
                                   a.sys_node_code as asys_node_code, 
                                   a.dns as adns, 
                                   a.sys_node_tag as asys_node_tag, 
                                   a.confi_lv_id || '级' as aconfi_lv_id,
                                   a.node_type as anode_type, 
                                   a.oprate_system as aoprate_system, 
                                   a.maintainer as amaintainer, 
                                   a.maintainer_phone as amaintainer_phone, 
                                   a.maintainer_email as amaintainer_email,
                                   a.is_register as ais_register, 
                                   d2t(a.r_time) as ar_time, 
                                   b.info_sys_name as binfo_sys_name, 
                                   c.agency_name as cagency_name 
                            from h_system_node as a
                            left join h_information_system as b 
                            on a.info_sys_id = b.info_sys_id
                            left join sys_agency_info as c 
                            on b.agency_id = c.agency_id
                            where a.state = '1' and a.sys_node_id = '%s' """ % (data['sys_node_id']))
        return json.dumps({
            "status": "success",
            "data": g.cursor.fetchall()
        })
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败'})


@app.route('/api/systemNode/new', methods=['get'])
@auth.permission('systemNode')
def get_new_count(_currUser):
    u"""查询同步重保变更数."""
    try:
        g.cursor.execute("""select count(1) as num from h_synchroniz_info where synchroniz_table = 'h_system_node' and person_id = '%s' and state = '1'""" % (_currUser['user']['person_id']))
        return json.dumps({
            "status": "success",
            "data": g.cursor.fetchone()['num']
        })
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败', "warn": str(e)})


@app.route('/api/systemNode/not', methods=['POST'])
@auth.permission('systemNode')
def get_not(_currUser):
    u"""查询未上报节点."""
    try:
        g.cursor.execute("""select r_id, feedback_state from h_unregistered_node""")
        return json.dumps({
            "status": "success",
            "data": g.cursor.fetchall()
        })
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败', "warn": str(e)})


@app.route('/api/systemNode/already', methods=['POST'])
@auth.permission('systemNode')
def get_already(_currUser):
    u"""查询已上报节点."""
    try:
        g.cursor.execute("""select r_id, track_state, add_time, feedback_time, feedback_person from h_unregistered_node""")
        return json.dumps({
            "status": "success",
            "data": g.cursor.fetchall()
        })
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败', "warn": str(e)})


@app.route('/api/systemNode/trackState', methods=['POST'])
@auth.permission('systemNode')
def get_state(_currUser):
    u"""获取反馈跟踪状态."""
    try:
        g.cursor.execute("""select track_state from h_unregistered_node""")
        return json.dumps({
            "status": "success",
            "data": g.cursor.fetchall()
        })
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败', "warn": str(e)})

# @app.route('/api/important/list_no_task', methods=['get'])
# def list_no_task():
#     u"""获取未配置任务重保."""
#     try:
#         # 当task_id为空的时候 且 重大安保存在 就是未配置的
#         g.cursor.execute("""select a.impro_id as impro_id,a.import_title as import_title 
#                             from h_import_protect_info as a 
#                             left join h_import_task_relation as b on a.impro_id = b.impro_id 
#                             where b.task_id is null and a.state = '1' """)
#         return json.dumps({
#             "status": "success",
#             "data": g.cursor.fetchall()
#         })
#     except Exception, e:
#         return json.dumps({"status": "except", 'msg': '查询失败'})
